import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    TextInput,
    ScrollView,
    ActivityIndicator,
} from 'react-native';
import moment from 'moment';
import HttpUtils from '../../../utils/HttpUtils';
import HttpUrls from '../../../utils/HttpUrls';
import Constant from '../../../utils/Constant'//全局变量
import Header from "../../../components/header";
import Loading from '../../../utils/Loading';
import PublishCarArrow from '../publishCar/components/PublishCarArrow';
import { ToastToUser } from '../../../utils/CustomToast';
import Picker from 'react-native-picker'
import DatePickerPart from '../../../components/Tool/DatePickerPart'
import { CarSaleStatus } from '../../../utils/Enum'
import { getImgUrl } from '../../../utils/ComFunction'
import AndroidConnent from '../../../utils/AndroidConnent';

const isIos = Platform.OS == 'ios';

let navigation

let pageSize = 20
let pageNo = 1;
let itemNo = 0;

const screenW = Dimensions.get('window').width;

export default class CarFoursReportPage extends Component {

    constructor(props) {
        super(props);
        let vcode = this.props.route && this.props.route.params && this.props.route.params.vcode ? this.props.route.params.vcode : ''
        this.state = {
            vcode,
            isRefresh: false,
            showFoot: 0,
            dataArray: []
        }
    }

    componentWillMount() {

    }

    componentWillUnmount() {

    }

    componentDidMount() {
        this.getFoursQueryHistory(true)
    }

    refreshData = () => {
        this.getFoursQueryHistory(true);
    }


    getFoursQueryHistory(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            vcode: this.state.vcode,
        }
        HttpUtils.postRequest(HttpUrls.maintenanceRecords, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ dataArray: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            dataArray: this.state.dataArray.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'VIN码:' + this.state.vcode} />

                <View style={{ flex: 1 }}>
                    <FlatList
                        data={this.state.dataArray}
                        renderItem={this.renderItemView.bind(this)}
                        extraData={this.state}
                        ListFooterComponent={this._renderFooter.bind(this)}
                        onEndReached={this._onEndReached.bind(this)}
                        onEndReachedThreshold={0.2}
                        onRefresh={this.refreshData}
                        refreshing={this.state.isRefresh}
                        ListEmptyComponent={this.renderEmpty.bind(this)}
                    />

                </View>

            </View>
        );
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderItemView({ item, index }) {
        return (
            <TouchableOpacity
                style={styles.itemBg}
                activeOpacity={0.8}
                onPress={() => {
                    let tempItem = item.value
                    let url = ''
                    if (tempItem.reportPdf) {
                        url = tempItem.reportPdf
                    } else if (tempItem.reportWapUrl) {
                        url = tempItem.reportWapUrl
                    } else if (tempItem.reportPics && tempItem.reportPics.length > 0) {
                        navigation.navigate('CarFoursPicReportPage', { reportPics: tempItem.reportPics })
                        return
                    }
                    console.log('url = ',url)

                    if(isIos){
                        navigation.navigate('WebView', { source: url, title: '报告详情' })
                    }else{
                        if(url.endsWith('.pdf')){
                            
                            AndroidConnent.pdfPreview({pdfUrl:url})
                        }else{
                            
                            navigation.navigate('WebView', { source: url, title: '报告详情' })
                        }
                    }
                    
                    
                }}
            >
                <View style={styles.itemBox}>
                    {
                        item.value.merchantLogoPic ?
                            <Image style={styles.companyImg} source={{ uri: getImgUrl(item.value.merchantLogoPic) }} />
                            :
                            <Image style={styles.companyImg} source={require('source/image/comm/sc_default.png')} />
                    }

                    <View style={styles.itemDesBox}>
                        <Text style={styles.itemTitleText} numberOfLines={1}>{item.value.merchantName}</Text>
                        <Text style={styles.itemDesText}>{item.value.createTime}</Text>
                    </View>
                    <Image style={styles.arrowImg} source={require('source/image/comm/icon_tree_arrow.png')} />
                </View>
            </TouchableOpacity>
        )
    }

    _renderFooter() {
        if (this.state.showFoot === 1) {
            return <View style={{height: Constant.bottomHeight}}/>;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        if (this.state.dataArray.length == 0) {
            return;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getFoursQueryHistory(false);
    }



}

const styles = StyleSheet.create({
    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f9f9f9',
    },

    itemBg: {
        width: '100%',
        height: 78,
        paddingTop: 10,
        paddingHorizontal: 10,
    },
    itemBox: {
        backgroundColor: '#fff',
        width: '100%',
        height: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        paddingHorizontal: 16,
    },
    companyImg: {
        width: 46,
        height: 46,
        borderRadius: 23,
    },
    itemDesBox: {
        flex: 1,
        flexDirection: 'column',
        marginLeft: 20,
        justifyContent: 'center',
        alignItems: 'flex-start',
    },
    itemTitleText: {
        fontSize: 15,
        color: '#333',
    },
    itemDesText: {
        marginTop: 8,
        fontSize: 12,
        color: '#999',
    },
    arrowImg: {
        marginLeft: 10,
        width: 15,
        height: 15
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

})